package com.me.mvc.controller;

import com.me.mvc.model.ModelUtils;
import com.me.mvc.model.entity.Client;
import com.me.mvc.model.validator.ClientValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Roman Uholnikov
 */
@Controller
public class Clients {

    @Autowired
    ClientValidator validator;

    @RequestMapping(value = "/clients", method = RequestMethod.GET)
    public ModelAndView showClients(ModelMap model, @RequestParam(value = "clientId", required = false, defaultValue = "0") int clientId) {
        if (clientId > 0) {
            List<Client> resutl = new LinkedList<Client>();
            resutl.add(ModelUtils.clientMap.get(clientId));
            return new ModelAndView("clients", "clients", resutl);
        } else {
            model.addAttribute("clientForm", new Client(ModelUtils.clientMap.size()+1 ,""));
            return new ModelAndView("clients", "clients", new LinkedList<Client>(ModelUtils.clientMap.values()));
        }
    }

    @RequestMapping(value = "/clients", method = RequestMethod.POST)
    public ModelAndView showClientsPost(ModelMap model, @ModelAttribute("clientForm") Client clientForm, BindingResult result) {
        validator.validate(clientForm, result);
        if(!result.hasErrors()) {
            ModelUtils.clientMap.put((int) clientForm.getId(), clientForm);
            model.addAttribute("clientForm", new Client(ModelUtils.clientMap.size()+1 ,""));
        }
        return new ModelAndView("clients", "clients", new LinkedList<Client>(ModelUtils.clientMap.values()));
    }

    @RequestMapping(value = "/clients/{clientId}", method = RequestMethod.GET)
    public String showForm(ModelMap model, @PathVariable("clientId") Integer clientId) {
        model.addAttribute("client", ModelUtils.clientMap.get(clientId));
//        createEmployee(clientId);
        return "client";
    }


    private void createEmployee(Integer id) {
        final String uri = MessageFormat.format("http://localhost:8080/clients/{0}/rest.json", id);


        RestTemplate restTemplate = new RestTemplate();
        HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        restTemplate.setMessageConverters((Arrays.<HttpMessageConverter<?>>asList(jsonConverter)));
        Client result = restTemplate.getForObject(uri, Client.class);

        System.out.println(result);
    }

}
